package org.geektimes.projects.user;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.stream.Stream;

/**
 * 应用配置
 *
 * @author Sanhong
 */
public class AppBootstrapper {
    @Resource(name = "jdbc/UserPlatformDB")
    private DataSource dataSource;

    /**
     * dev,uat,prd....
     */
    private String profile;

    public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 执行一些初始化逻辑
     */
    @PostConstruct
    public void init() {
        /**
         * 开发环境初始化
         */
        if ("dev".equals(profile)) {
            initDB();
        }
    }

    private void initDB() {
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement())
        {
            try {
                String[] initDDL = getInitDDL();
                Stream.of(initDDL).forEach(ddl -> {
                    try {
                        statement.executeUpdate(ddl);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                });
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
        }
    }

    private String[] getInitDDL() throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL ddlURL = classLoader.getResource("META-INF/db/DDL/users_table_ddl.sql");
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf = new BufferedReader(new FileReader(ddlURL.getFile()));
        String s = null;
        // 使用readLine方法，一次读一行
        while((s = bf.readLine())!=null){
            buffer.append(s.trim());
        }
        String ddls = buffer.toString();
        return ddls.split(";");
    }
}
